import { API_URLS } from '@/base/interface-config';
import { axiosRequest } from '@/utils/http-service';

// 定义登录接口返回类型
interface LoginResponse {
  operateSuccess: boolean;
  msg: string;
  accessToken: string;
  refreshToken: string;
  accountName: string;
  baseAccountQueryVo: {
    accountId: string;
    personId: string;
    personName: string;
    // ... 其他字段
  };
  datas: Array<{
    funcId: string;
    funcName: string;
    url: string;
    imgUrl: string;
    menuSeq?: number;
    // ... 其他字段
  }>;
}

// 定义登录参数类型
interface LoginParams {
  accountName: string;
  password: string;
}

export const useUserStore = defineStore('user', () => {
  const login = async (params: LoginParams) => {
    try {
      const res: any = await axiosRequest<LoginResponse>({
        url: API_URLS.login,
        method: 'POST',
        data: params
      });

      if (res.data.operateSuccess) {
        // 保存token和用户信息
        localStorage.setItem('token', res.data.accessToken);
        localStorage.setItem('refreshToken', res.data.refreshToken);
        localStorage.setItem('userInfo', JSON.stringify(res.data.baseAccountQueryVo));

        // 根据 menuSeq 排序后保存菜单
        const sortedMenus = res.data.datas.sort((a, b) => (a.menuSeq || 0) - (b.menuSeq || 0));
        localStorage.setItem('menus', JSON.stringify(sortedMenus));

        return true;
      }
      return false;
    } catch (error) {
      console.error('登录失败:', error);
      return false;
    }
  };

  const logout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
    localStorage.removeItem('userInfo');
    localStorage.removeItem('menus');
  };

  const hasPermission = (permission: string) => {
    const menus = JSON.parse(localStorage.getItem('menus') || '[]');
    return menus.some((menu: any) => menu.url === permission);
  };

  return {
    login,
    logout,
    hasPermission
  };
});
